const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')

module.exports = {
  mode: process.env.NODE_ENV === 'development' ? 'development' : 'production',
  entry: './js/main.js',
  output: {
    path: path.resolve(__dirname, 'lottery2'),
    filename: 'js/main.js',
    chunkFilename: 'js/[name].js',
    publicPath: './',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              [
                '@babel/preset-env',
                {
                  targets: {
                    esmodules: true,
                  },
                },
              ],
            ],
            plugins: [
              '@babel/plugin-proposal-nullish-coalescing-operator',
              '@babel/plugin-proposal-logical-assignment-operators',
            ],
          },
        },
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
        generator: {
          filename: 'css/[name][ext]',
        },
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'images/[hash][ext][query]',
        },
      },
      {
        test: /\.(mp3|m4a|wav)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'audio/[name][ext]',
        },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html',
      filename: 'index.html',
      inject: true,
      minify: {
        collapseWhitespace: true,
        removeComments: true,
      },
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'js/tagcanvas.js',
          to: 'js',
        },
        {
          from: 'audio',
          to: 'audio',
          noErrorOnMissing: true,
        },
        {
          from: 'img',
          to: 'img',
          noErrorOnMissing: true,
        },
        {
          from: 'css',
          to: 'css',
          noErrorOnMissing: true,
        },
      ],
    }),
  ],
  externals: {
    vue: 'Vue',
    zepto: 'Zepto',
    layui: 'layui',
  },
  performance: {
    hints: false,
    maxAssetSize: 3000000,
    maxEntrypointSize: 3000000,
  },
  optimization: {
    splitChunks: {
      chunks: 'async',
      minSize: 20000,
      maxSize: 0,
      cacheGroups: {
        defaultVendors: false,
        default: false,
      },
    },
  },
  resolve: {
    extensions: ['.js'],
  },
  devServer: {
    static: {
      directory: path.join(__dirname, 'lottery2'),
    },
    compress: true,
    port: 8090,
    hot: true,
    historyApiFallback: true,
  },
}
